<?php
/**
 * Log
 *
 * myLog(3,"este es un mensaje");
 *
 *
 * @params $pLevel int Level of log 1-critical, 2-warning, 3-info,
 * @params $pValue Mixed Value to log
 * @params $toDB if is logued in db
 * @params $type the type of log
 */

function myLogDB($msg){
    myLog(APP_DEBUG_LEVEL,$msg,$toDB=false,$type='db errors');        
}

function myLog($pLevel,$pValue,$toDB=false,$type='default'){

    if( $pLevel <= APP_DEBUG_LEVEL){
      	$pValue = print_r($pValue,true);
      	$time = time();
      	$PHPSESSID = $_REQUEST['PHPSESSID'];
      	$APP_DEBUG_TOKEN = APP_DEBUG_TOKEN;
      	$line = str_pad($input, 80,'-');
        error_log("\n{$line}\n[{$time}]::{$PHPSESSID}::{$APP_DEBUG_TOKEN}\n{$line}\n{$pValue}", 3, APP_LOG);

        if($toDB){
            $database = getDatabase();
            $data['value']=$pValue;
            $data['type']=$type;
            $data['session']=serialize($_SESSION);
            $data['get']=serialize($_GET);
            $data['post']=serialize($_POST);
            $data['session_id']=session_id();
            $database->insert('logs',$data);

        }
    }

}



/**
 * -----------------------------------------------------------------------------
 * Clean functions
 * -----------------------------------------------------------------------------
 */
if (get_magic_quotes_gpc()) {
    function magicQuotes_awStripslashes(&$value, $key) {$value = stripslashes($value);}
    $gpc = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    array_walk_recursive($gpc, 'magicQuotes_awStripslashes');
}
function _trim(&$value){
    $value = trim($value);
}

function array_trim($arr){
    array_walk($arr,"_trim");
    return $arr;
}





/**
 * -----------------------------------------------------------------------------
 * Database
 * -----------------------------------------------------------------------------
 */
function getDatabase(){
    global $db;
    if(!$db){
        $db = new myDb("mysql:host=".DATABASE_SERVER.";port=".DATABASE_PORT.";dbname=".DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD);
        $db->setErrorCallbackFunction("myLogDB");
    }
    return $db;
}

/**
 * -----------------------------------------------------------------------------
 * configuracion
 * -----------------------------------------------------------------------------
 */

function loadConfig(){
	require_once 'Config.php';

	// Inicializamos la configuracion y las ponenemos en constantes
	$file = APP_DIR.'/lib/config.xml';
	$conf = new Config();
	$root = $conf->parseConfig($file, 'xml');
	if (PEAR::isError($root)) {
		echo 'Error reading config: ' . $root->getMessage() . "\n";
		exit(1);
	}
	$config = $root->toArray();
	foreach($config['root']['conf'] as $k=>$s){
		foreach($s as $_k=>$_v){
			$define[strtoupper("{$k}_{$_k}")]=$_v;
		}
	}
	foreach($define as $k=>$v){
		foreach($define as $_k=>$_v){
			if(stripos($_v,$k)!==false){
				$define[$_k]=str_ireplace($k,$v,$_v);
			}
		}
	}
	foreach($define as $k=>$v){
		foreach($define as $_k=>$_v){
			if(stripos($_v,$k)!==false){
				$define[$_k]=str_ireplace($k,$v,$_v);
			}
		}
	}
	foreach($define as $k=>$v){
		define($k, $v);
	}

	//print_r(get_defined_constants (true));
}

/**
 * -----------------------------------------------------------------------------
 * Images
 * -----------------------------------------------------------------------------
 */
 
function getImage($src,$w,$h){
   $url = APP_URL."/lib/timthumb/timthumb.php?src={$src}&w={$w}&h={$h}";
   return $url;
} 

/**
 * -----------------------------------------------------------------------------
 * simple cache
 * -----------------------------------------------------------------------------
 */

function cache_key($value){
    return CACHE_DIR.'/'.md5($value).session_id();
}

function cache_get($key){ 
    $key = cache_key($key); 
    if(!file_exists($key)) return false;
    
    $content = file_get_contents($key);
    return unserialize($content);
}

function cache_put($key,$value){
    $key = cache_key($key);

    $value = serialize($value);
    file_put_contents($key,$value);
}
